﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using FbHelperWP7NonUi.BookStorage.PhoneStorage;
using FbHelperWP7NonUi.TextHelpers;

namespace FbHelperWP7.Controls
{
    public partial class PhoneStorageControl : UserControl
    {
        internal delegate void BookSelected( Book book );
        internal event BookSelected BookSelectedEvent;

        private PhoneDirectory currentDirectory = PhoneDirectory.Root;

        public PhoneStorageControl()
        {
            InitializeComponent();

            UpdateItems();
        }

        private void UpdateItems()
        {
            directoryName.Text = currentDirectory.Name;
            subItems.Items.Clear();

            FillDirectories();
            FillFiles();
        }

        private void FillDirectories()
        {
            foreach (string subDirectory in currentDirectory.GetSubdirectories())
            {
                ListBoxItem item = CreateAndAddSubItem( subDirectory );
                item.Tap += new EventHandler<GestureEventArgs>( DirectoryItemTap );
                item.FontStyle = FontStyles.Normal;
            }
        }

        private void ChangeToDirectory( string subdirectoryName )
        {
            currentDirectory = currentDirectory.OpenDirectory( subdirectoryName );

            UpdateItems();
        }

        private void FillFiles()
        {
            foreach (string fileName in currentDirectory.GetFiles())
            {
                ListBoxItem item = CreateAndAddSubItem( System.IO.Path.GetFileNameWithoutExtension( fileName ) );
                item.Tap += new EventHandler<GestureEventArgs>( FileItemTap );
                item.FontStyle = FontStyles.Italic;
                item.Tag = fileName;
            }
        }

        private ListBoxItem CreateAndAddSubItem( string name )
        {
            ListBoxItem result = new ListBoxItem()
            {
                Content = name
            };

            subItems.Items.Add( result );

            return result;
        }

        private void DirectoryItemTap( object sender, GestureEventArgs e )
        {
            ListBoxItem item = sender as ListBoxItem;

            ChangeToDirectory( item.Content.ToString() );
        }

        private void FileItemTap( object sender, GestureEventArgs e )
        {
            if (BookSelectedEvent != null)
            {
                ListBoxItem item = sender as ListBoxItem;

                Book book = currentDirectory.OpenFile( (string)item.Tag );

                BookSelectedEvent( book );
            }
        }
    }
}
